//
//  SearchViewController.m
//  chanyou
//
//  Created by 高爽 on 15-1-13.
//  Copyright (c) 2015年 wanli. All rights reserved.
//

#import "SearchViewController.h"

#import "ViewController.h"

#import "ConnectModel.h"

#import "NotesViewController.h"
#import "DestinationsViewController.h"

#define SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)
#define SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)


@interface SearchViewController ()<UITextFieldDelegate>
@end

@implementation SearchViewController
- (void)dealloc
{
    [_cityArray release];
    [_searchArray release];
    [_location release];
    [_dataArray release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.location = _location;
        self.dataArray = _dataArray;
        self.tag = 53;
        self.searchArray = [NSMutableArray arrayWithObjects:@"新加坡", @"日本", @"美国",@"马尔代夫", @"澳大利亚", @"德国", @"法国", @"英国", @"土耳其", @"马来西亚", @"菲律宾", @"泰国", @"西班牙", @"墨西哥", @"奥地利", @"希腊", @"挪威", @"南极", nil];
        self.cityArray = [NSMutableArray arrayWithObjects:@"新疆", @"台湾",@"澳门", @"云南", @"呼伦贝尔", @"成都", @"厦门", @"三亚", @"拉萨", @"青海", @"平遥", @"广州", @"安徽", @"哈尔滨", @"大连", @"洛阳", @"秦皇岛", @"贵州", nil];
    }return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"youayou" style:UIBarButtonItemStylePlain target:self action:nil];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(cancleAction)];
    
    // 背景图
    UIImage *img = [UIImage imageNamed:@"background vague.png"];
    UIImageView *imv = [[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)] autorelease];
    imv.image = img;
    [self.view addSubview:imv];

    // searchBar
//    self.mySearch = [[[UISearchBar alloc] initWithFrame:CGRectMake(10, 30, SCREEN_WIDTH - 60, 40)] autorelease];
//    // _location = _mySearch.text;
//    [_mySearch setPlaceholder: @"搜索"];
//    _mySearch.delegate = self;
//    [_mySearch setBarStyle:UIBarStyleBlackOpaque];
//    // [_mySearch setShowsCancelButton:YES];
//    [self.view addSubview:_mySearch];
    
    self.searchFrame = [[UIView alloc] initWithFrame:CGRectMake(10, 30, SCREEN_WIDTH - 20, 40)];
    _searchFrame.backgroundColor = [UIColor orangeColor];
    // 圆角
    self.searchFrame.layer.cornerRadius = 40 / 4;
    UIButton *searchPic = [[UIButton alloc] initWithFrame:CGRectMake(5, 10, 20, 20)];
    [searchPic setBackgroundImage:[UIImage imageNamed:@"NavBarIconSearch_blue.png"] forState:UIControlStateNormal];
    [searchPic addTarget:self action:@selector(searchNameAction) forControlEvents:UIControlEventTouchUpInside];
    self.searchField = [[UITextField alloc] initWithFrame:CGRectMake(30, 3, SCREEN_WIDTH - 26, 34)];
    [_searchField setPlaceholder:@"search"];
    _searchField.delegate = self;

    // _searchField.backgroundColor = [UIColor yellowColor];
    self.searchField.font = [UIFont fontWithName:@"AvenirNext-Regular" size:18.0];
    self.searchField.textColor = [UIColor grayColor];
    [self.view addSubview:_searchFrame];
    [self.searchFrame addSubview:self.searchField];
    [_searchFrame addSubview:searchPic];
    

    // seg
    UISegmentedControl *seg = [[[UISegmentedControl alloc] initWithFrame:CGRectMake(20, 80, SCREEN_WIDTH - 40, 25)] autorelease];
    [seg setBackgroundColor:[UIColor colorWithRed:231/256 green:231/256 blue:231/256 alpha:1.0]];
    [seg insertSegmentWithTitle:@"国外" atIndex:0 animated:YES];
    [seg insertSegmentWithTitle:@"国内" atIndex:1 animated:YES];
    [seg addTarget:self action:@selector(segAction:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:seg];
    
}
- (void)segAction:(UISegmentedControl *)seg
{
    NSInteger index = seg.selectedSegmentIndex;
    NSInteger num = 0;
    switch (index) {
        case 0:
            for (int i = 0; i < [_searchArray count] / 3; i++) {
                for (int j = 0; j < 3; j++) {
                    UIButton * country = [[[UIButton alloc] initWithFrame:CGRectMake(10 + j * (SCREEN_WIDTH - 20 - 10) / 3 + j * 5, 130 + i * 35, (SCREEN_WIDTH - 30) / 3, 25)] autorelease];
                    [country addTarget:self action:@selector(countryAction:) forControlEvents:UIControlEventTouchUpInside];
                    [country setTitle:[_searchArray objectAtIndex:num] forState:UIControlStateNormal];
                    [country setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                    num++;
                    country.tag = _tag;
                    _tag = _tag + 2;
                    country.layer.cornerRadius = 4;
                    country.backgroundColor = [UIColor grayColor];
                    [self.view addSubview:country];
                }
            }
            
            break;
        case 1:
            for (int i = 0; i < [_cityArray count] / 3; i++) {
                for (int j = 0; j < 3; j++) {
                    _tag = 10;
                    UIButton *country = [[[UIButton alloc] initWithFrame:CGRectMake(10 + j * (SCREEN_WIDTH - 20 - 10) / 3 + j * 5, 130 + i * 35, (SCREEN_WIDTH - 30) / 3, 25)] autorelease];
                    [country addTarget:self action:@selector(countryAction:) forControlEvents:UIControlEventTouchUpInside];
                    [country setTitle:[_cityArray objectAtIndex:num] forState:UIControlStateNormal];
                    [country setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                    num++;
                    country.tag = _tag;
                    _tag = _tag + 2;
                    country.layer.cornerRadius = 4;
                    country.backgroundColor = [UIColor grayColor];                   [self.view addSubview:country];
                }
                
            }
            break;
        default:
            break;
    }
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if ([textField isFirstResponder]) {
        [textField setKeyboardType:UIKeyboardTypeWebSearch];
    }
}

- (void)searchNameAction
{
    NSLog(@"search");

    BOOL hasText = self.searchField.text.length != 0;
    if (hasText) {
        _location = _searchField.text;
        
    }
    NSLog(@"location = %@", self.location);

    NSMutableDictionary *DD = [NSMutableDictionary dictionaryWithObjectsAndKeys:_location,  @"name", nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(passAction:) name:@"PASSID" object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"PASSDATA" object:self userInfo:DD];
    
    [self connectParser];
}
- (void)passAction:(NSNotification *)noti
{
    _destination_id = [noti.userInfo objectForKey:@"ID"];
    NSLog(@"idid = %@", _destination_id);
}

- (void)countryAction:(UIButton *)sender
{
    NSLog(@"country!!");
    self.tagId = [NSString stringWithFormat:@"%ld", (long)sender.tag];
    NSLog(@"tag = %@", _tagId);
    NotesViewController *note = [[[NotesViewController alloc] init] autorelease];
    // UINavigationController *na = [[[UINavigationController alloc] initWithRootViewController:note] autorelease];
    UIButton *back = [[UIButton alloc] initWithFrame:CGRectMake(10, 30, 25, 25)];
    back.backgroundColor = [UIColor cyanColor];
    back.imageView.image = [UIImage imageNamed:@"back.png"];
    [back addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    // [na.view addSubview:back];
    note.destination_id = self.tagId;
    // [self presentViewController:na animated:YES completion:nil];
    [self.navigationController pushViewController:note animated:YES];
}
- (void)cancleAction
{
    NSLog(@"cancle");
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)backAction
{
    NSLog(@"back");
    [self dismissViewControllerAnimated:YES completion:nil];
}

// 解析
- (void)connectParser
{
    
    NSString *pa = [NSString stringWithFormat:@"http://chanyouji.com/api/search/trips.json?q=%@&page=1", _location];
    NSString *path = [pa stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"@@@@@@-==%@", path);
    
    
    [ConnectModel connectModelWithUrl:path parmaters:nil finished:^(NSData *data) {
        
        self.dataArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        if (! _dataArray) {
            NSLog(@"无数据");
        }
        
        NotesViewController *note = [[NotesViewController alloc] init];
        note.destination_id = self.destination_id;
        // [self presentViewController:note animated:YES completion:nil];
        [self.navigationController pushViewController:note animated:YES];
        
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
